package com.xzz.directprint.service;

/**
 * @Author: zhanglm
 * @CreateDate: 2024-12-03 16:12
 * @FullNameClass: com.xzz.directprint.service.FileSearch
 * @Description:
 */
import java.io.File;
import java.io.FileFilter;

public class FileSearchService {

    public static File findFileByName(File directory, final String fileName) {
        if (directory == null || !directory.isDirectory()) {
            return null;
        }

        File[] files = directory.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return file.isFile() && file.getName().equals(fileName);
            }
        });

        if (files != null && files.length > 0) {
            return files[0]; // 返回找到的第一个文件
        }

        // 递归搜索子目录
        File[] subDirectories = directory.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return file.isDirectory();
            }
        });

        if (subDirectories != null) {
            for (File subDirectory : subDirectories) {
                File foundFile = findFileByName(subDirectory, fileName);
                if (foundFile != null) {
                    return foundFile;
                }
            }
        }

        return null; // 如果没有找到文件，返回null
    }

    public static void main(String[] args) {
        File directory = new File("C:/start/directory"); // 指定搜索的起始目录
        File foundFile = findFileByName(directory, "example.txt"); // 要搜索的文件名
        if (foundFile != null) {
            System.out.println("File found: " + foundFile.getAbsolutePath());
        } else {
            System.out.println("File not found.");
        }
    }
}
